<?php
/**
 * CopyService.php class file.
 * @author wudg <544038230@qq.com>
 * @date 2021/1/17- 下午4:18
 */

namespace common\jobs\services;


use common\jobs\dao\PddAuthCatsDao;
use common\jobs\dao\PddGoodsCatTemplateDao;
use common\jobs\models\ComProducts;
use common\components\api\isv\Goods;
use common\helpers\AmountHelper;
use common\helpers\ImagesHelper;
use common\helpers\StringHelper;
use common\exception\CopyException;
use common\models\pdd\PddAuthCats;

class CopyService
{
    /**
     * 检查类目是否允许
     * @param int $catId
     * @param int $uid
     * @param int $mall_id
     * @return bool
     * @throws \common\exception\ServicesException
     * @throws \common\exception\ValidatorException
     */
    public function checkCatIsAuthorization(int $catId,int $uid,int $mall_id)
    {

        $authCids = $this->getMallAuthCid($uid,$mall_id);
        $pid = (new GoodsCatService())->getCatesByCid($catId);
        /**
         * 不存在直接不检测了
         */
        if(!isset($pid[0]['id'])) return true;
        $dbPid = $pid[0]['id'];
        if(in_array($dbPid,$authCids))
        {
            return true;
        }
        return false;

    }

    /**
     * 返回格式化后的 写入com_spider 格式数据
     * @param ComProducts $comProducts
     * @return string
     */
    public function transToComProduct(ComProducts $comProducts)
    {

        $skus = $productInfo = [];

        foreach($comProducts->skus as $k => $sku)
        {
            $tmp =[];
            $tmp['skuId'] = $sku->skuId;
            $tmp['stock'] = $sku->stock;
            $tmp['price'] = AmountHelper::fenToYuan($sku->price);
            $tmp['sale_price'] = isset($sku->sale_price) && !empty($sku->sale_price) ? AmountHelper::fenToYuan($sku->sale_price):  AmountHelper::fenToYuan($sku->price);
            $tmp['properties'] = $sku->properties;
            $tmp['properties_name'] = $sku->properties_name;
            array_push($skus,$tmp);
        }
        $productInfo = [
            'title' => $comProducts->title, //商品标题信息
            'skus' => $skus, //sku属性信息
            'video' => StringHelper::jsonDecode($comProducts->detail->video) ?? [], //视频地址
            'prices' => AmountHelper::fenToYuan($comProducts->prices), //价格
            'num_iid' => $comProducts->num_iid, //商品主键
            'platform' => $comProducts->platform, //平台
            'cid' => $comProducts->cid, //商品类目id
            'attr' => StringHelper::jsonDecode($comProducts->detail->attr) ?? [], //属性信息
            'main_pic' => $comProducts->main_pic, //封面图
            'sku_img' => StringHelper::jsonDecode($comProducts->detail->sku_img) ?? [],//sku 图
            'mall_id' => $comProducts->mall_id, //所属店铺id
            'mall_name' => $comProducts->mall_name, //所属店铺名称
            'pics' => StringHelper::jsonDecode($comProducts->detail->pics) ?? [], //主图信息
            'pc_desc' => $comProducts->detail->pc_desc, //电脑端详细
            'm_desc' => $comProducts->detail->m_desc, //移动端详细
            'extend_data' => StringHelper::jsonDecode($comProducts->detail->extend_data) ?? [], //扩展信息
        ];
        $productInfo['detail_gallery'] = ImagesHelper::getStrImagesList($comProducts->detail->pc_desc); //提取描叙中的所有图片
        return StringHelper::jsonEncode($productInfo);
    }


    /**
     * 外部属性预测
     * @param int $catId
     * @param int $mall_id
     * @param string $outPropertyName
     * @param string $outPropertyValue
     * @return array
     * @throws \common\exception\ServicesException
     */
    public function outPropertyMapping(int $catId,int $mall_id,string $outPropertyName,string $outPropertyValue = '')
    {
        return  (new Goods())->pddGoodsOutPropertyMappingGet([
            'cat_id' => $catId,
            'out_property_name' => $outPropertyName,
            'out_property_value_name' => $outPropertyValue,
        ],$mall_id);
    }


    /**
     * 拼多多 附件上传
     * @param string $imgUrl
     * @param int $mall_id
     * @return mixed
     * @throws \common\exception\ServicesException
     */
    public function uploadImageToPdd(string $imgUrl,int $mall_id)
    {
        if($imgUrl){
            //$imgUrl = ImagesHelper::base64EncodeImage($imgUrl);
            //$imageFile = ImagesHelper::fileToBold($imgUrl);

            $responesImg = (new Goods())->pddGoodsImageUpload($imgUrl,$mall_id);
            if($responesImg){
                return $responesImg;
            }else{
                return '';
            }
        }else{
            return '';
        }

    }


    /**
     * 通过类目获取商品属性信息
     * @param int $cid
     * @param int $mall_id
     * @return array
     * @throws \common\exception\ServicesException
     * @throws \common\exception\ValidatorException
     */
    public function getSpecByCid(int $cid,int $mall_id)
    {

        $catTemplateDao = new PddGoodsCatTemplateDao();

        $templateInfo = $catTemplateDao->getTemplateByCid($cid);

        if(!$templateInfo || $templateInfo->sync_time < (time()-86400))
        {
            $specInfo = (new Goods())->pddGoodsCatTemplateGet($cid,$mall_id);
            if(!$specInfo){
                return [];
            }

            if(!$templateInfo)
            {
                $templateInfo = $catTemplateDao->insertOrUpdateData([
                    'id' => $specInfo['id'],
                    'cat_id' => $cid,
                    'max_sku_num' => $specInfo['max_sku_num'],
                    'sync_time' => time(),
                    'properties' => json_encode($specInfo['properties'],JSON_UNESCAPED_UNICODE),
                    'choose_all_qualify_spec' => $specInfo['choose_all_qualify_spec'] == true ? 1 : 0,
                    'input_max_spec_num' => $specInfo['input_max_spec_num'],
                    'single_spec_value_num' => $specInfo['single_spec_value_num'],
                ]);
            }else{
                $catTemplateDao->updateData($templateInfo,[
                    'cat_id' => $cid,
                    'max_sku_num' => $specInfo['max_sku_num'],
                    'sync_time' => time(),
                    'properties' => json_encode($specInfo['properties'],JSON_UNESCAPED_UNICODE),
                    'choose_all_qualify_spec' => $specInfo['choose_all_qualify_spec'] == true ? 1 : 0,
                    'input_max_spec_num' => $specInfo['input_max_spec_num'],
                    'single_spec_value_num' => $specInfo['single_spec_value_num'],
                ]);
            }
        }
        $templateInfo->properties = json_decode($templateInfo->properties,1);
        return  $templateInfo->toArray();

    }


    /**
     * @param int $uid
     * @param int $mall_id
     * @return array|mixed
     * @throws \common\exception\ServicesException
     * @throws \common\exception\ValidatorException
     */
    private function getMallAuthCid(int $uid,int $mall_id)
    {

        $authCids = [];
        $dbInfo = PddAuthCats::findOne(['uid'=>$uid,'mall_id'=>$mall_id]);

        if($dbInfo && $dbInfo->sync_at > time()-86400)
        {
            $authCids = json_decode($dbInfo->cat_ids,true);
        }else{
            $goodsIsv = new Goods();

            $mallCatIds = $goodsIsv->pddGoodsAuthorizationGet(0,$mall_id);

            if(count($mallCatIds['goods_cats_list']))
            {
                foreach ($mallCatIds['goods_cats_list'] as $k => $item)
                {
                    array_push($authCids,$item['cat_id']);
                }
            }

            (new PddAuthCatsDao())->insertData([
                'uid' => $uid,
                'mall_id' => $mall_id,
                'cat_ids' => json_encode($authCids,JSON_UNESCAPED_UNICODE),
                'sync_at' => time()
            ]);
        }
        return $authCids;

    }
}